package com.holystone.orca.sys.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.holystone.orca.base.controller.BaseController;
import com.holystone.orca.common.JSONMapper;
import com.holystone.orca.common.PageData;
import com.holystone.orca.sys.common.SystemConstant;
import com.holystone.orca.sys.mybatis.model.SysPrivilege;
import com.holystone.orca.sys.service.ISysPrivilegeRoleService;
import com.holystone.orca.sys.service.ISysPrivilegeService;
 
@Controller
@RequestMapping("/sys/privilege_management")
public class SysPrivilegeController extends BaseController {

	private static Logger logger = Logger.getLogger(SysPrivilegeController.class);
	
	private String baseUrl = "sys/privilege_management/";
	
	@Resource(name="privilegeService")
	private ISysPrivilegeService sysPrivilegeService;
	@Autowired
	private ISysPrivilegeRoleService sysPrivilegeRoleService;
	
	
    @RequestMapping("/menuPrivilegeList")
    public ModelAndView menuPrivilegeList(){
    	ModelAndView model = new ModelAndView(baseUrl+"privilege_management");
        return model;
    }
    
    //初始化ztree，查询出权限信息，拼接字符串，前端生成树
    @ResponseBody
    @RequestMapping("/initLookPrivilege")
    public ModelMap initLookPrivilege(){
    	ModelMap modelMap = new ModelMap();
    	List<SysPrivilege> privilegeList=sysPrivilegeService.selectAllPrivilege();
    	String nodes = "";
    	for(int i=0;i<privilegeList.size();i++){
    		 nodes +="{id:"+privilegeList.get(i).getPriId()+", pId:"
    	+privilegeList.get(i).getPriPid()+", name:\""+privilegeList.get(i).getPriName()
    	+"\" , open:true},";
    		//lstTree.add(nodes);
    	}
    	if(nodes != ""){
    		nodes = nodes.substring(0, nodes.length() - 1);
    	}
    	nodes ="["+nodes+"]";
    	modelMap.put("lstTree", nodes);
    	return modelMap;
    }
    
    //分页，点击树的分支，显示出当前权限的数据和其子类的信息
    @ResponseBody
    @RequestMapping("/pagingPrivilegeManagement")
    public ModelMap pagingPrivilegeManagement(String  iPageNo, String iPageSize,String priId,ModelMap modelMap){
    	int pageindex = iPageNo!=null?Integer.parseInt(iPageNo):SystemConstant.default_pageNum;
        int pagesize = iPageSize!=null?Integer.parseInt(iPageSize):SystemConstant.default_pageSize;
        PageData pageData = new PageData();
        List<SysPrivilege> sysPrivilege = null; 
        List<Integer> list = new ArrayList<Integer>(); 
        List<SysPrivilege> sysPrivilegeList=null;
		try {
			sysPrivilegeList = sysPrivilegeService.sysPrivilegeList(priId);
			if(sysPrivilegeList.size() != 0){
				//如果点击的为父级菜单，则显示其子类菜单
				for(int i=0;i<sysPrivilegeList.size();i++){
					list.add(sysPrivilegeList.get(i).getPriPid());
				}
					pageData = sysPrivilegeService.pagingSysPrivilegeList(pageindex, pagesize, "priId", priId,true);
				sysPrivilege = sysPrivilegeService.selectPrivilegePriName(list);
			}else{
				//如果点击子类菜单，则显示自己
				pageData = sysPrivilegeService.pagingSysPrivilegeList(pageindex, pagesize, "priId", priId,false);
				sysPrivilege = sysPrivilegeService.selectPriviByPriId(Integer.parseInt(priId));
			}
        }catch(Exception e){
            logger.error(e,e);
        }
        
        modelMap=JSONMapper.createReturnMap(null, pageData, null);
        modelMap.put("sysPrivilege", sysPrivilege);
        return modelMap;
    }
    
    
    
    //添加修改页面，分别绑定信息
    @RequestMapping(value="/addEditPrivilege")
	public ModelAndView addEditPrivilege(String priId,String opera){
		logger.debug(">>>initEditSysPrivilege(String priId,String opera)初始化权限添加修改页面");
		ModelAndView view = new ModelAndView(baseUrl+"add_edit_privilege");
		if(opera!=null&&opera.equals("add_bro")){//添加
			SysPrivilege sysPrivilege=null;
			try {
				sysPrivilege = sysPrivilegeService.selectPriByPriId(Integer.parseInt(priId));
			} catch (Exception e) {
				logger.error(e,e);
			}
			view.addObject("priId",priId);
			view.addObject("sysPri",sysPrivilege);//查询点击的权限的父类信息，传到页面，用于添加时初始化父类型信息
			view.addObject("msg","add_bro");//编辑为添加兄弟节点信息，用于页面是添加还是修改的按钮判断
		}else if(opera!=null&&opera.equals("add_chi")){
			SysPrivilege sysPrivilege=null;
			try {
				sysPrivilege = sysPrivilegeService.selectParentPrivilegeByPriId(Integer.parseInt(priId));
			} catch (Exception e) {
				logger.error(e,e);
			}
			view.addObject("priId",priId);
			view.addObject("sysPri",sysPrivilege);//查询点击的权限的信息，传到页面，用于添加时初始化父类型信息
			view.addObject("msg","add_chi");
		}else if(opera!=null&&opera.equals("edit")){//修改
			SysPrivilege sysPrivilege=null;
			SysPrivilege sysPrivilege2=null;
			try {
				sysPrivilege = sysPrivilegeService.selectParentPrivilegeByPriId(Integer.parseInt(priId));
				sysPrivilege2 = sysPrivilegeService.selectPriByPriId(Integer.parseInt(priId));
			} catch (Exception e) {
				logger.error(e,e);
			}
			view.addObject("priId",priId);
			view.addObject("sysPri",sysPrivilege2);//查询当前权限父类的信息，用于显示父类信息
			view.addObject("sysPrivilege",sysPrivilege);//查询当前权限信息，用于初始化修改页面信息
		}
		logger.debug("<<<initEditSysPrivilege(SysPrivilege sysprivilege)");
		return view;
	}
    
    //点击保存兄弟节点信息，添加
    @ResponseBody
    @RequestMapping("/addBroPrivilege")
    public ModelMap addBroPrivilege(SysPrivilege sysPrivilege){
    	boolean flag=false;
    	try {
			flag=sysPrivilegeService.addBroPrivilege(sysPrivilege);
		} catch (Exception e) {
			 logger.error(e,e);
		}
    	return JSONMapper.createReturnMap(null, null, flag);
    } 
    
    //点击添加子类权限信息，添加
    @ResponseBody
    @RequestMapping("/addChildPrivilege")
    public ModelMap addChildPrivilege(SysPrivilege sysPrivilege,ModelMap modelMap){
    	boolean flag=false;
    	String priType="";
    	String msg="";
    	try {
    		//获取当前点击的权限信息，添加其子类信息
    		priType = sysPrivilegeService.selectParentPrivilegeByPriId(sysPrivilege.getPriId()).getPriType();
    		if("9fa".equals(priType)){
    			sysPrivilege.setPriType("9fb");
    			flag=sysPrivilegeService.addChildPrivilege(sysPrivilege);
    		}else if("9fb".equals(priType)){
    			sysPrivilege.setPriType("9fc");
    			flag=sysPrivilegeService.addChildPrivilege(sysPrivilege);
    		}else if("9fc".equals(priType)){
    			sysPrivilege.setPriType("9fd");
    			flag=sysPrivilegeService.addChildPrivilege(sysPrivilege);
    		}else if("9fd".equals(priType)){
    			//如果当前权限为四级节点，则不能再添加其子节点
    			msg="不能添加子节点了";
    		}
		} catch (Exception e) {
			 logger.error(e,e);
		}
    	modelMap = JSONMapper.createReturnMap(null, null, flag);
    	modelMap.put("msg", msg);
    	return modelMap;
    }
    
    //点击修改信息
    @ResponseBody
    @RequestMapping("/editPrivilege")
    public ModelMap editPrivilege(SysPrivilege sysPrivilege,String oldActionPri,ModelMap modelMap){
    	boolean flag=false;
    	try {
    		flag=sysPrivilegeService.editPrivilege(sysPrivilege,oldActionPri);
		} catch (Exception e) {
			 logger.error(e,e);
		}
    	modelMap = JSONMapper.createReturnMap(null, null, flag);
    	return modelMap;
    }
    

    //删除点击的权限
    @ResponseBody
    @RequestMapping("/deletePrivilege")
    public ModelMap deletePrivilege(int priId){
    	boolean flag=false;
    	try {
    		flag = sysPrivilegeService.delPrivilege(priId);
    	} catch (Exception e) {
    		logger.error(e,e);
    	}
    	return JSONMapper.createReturnMap(null, null, flag);
    }
    
    //多项删除，删除选中的权限
    @ResponseBody
    @RequestMapping("/deleteSelectPrivilege")
    public ModelMap deleteSelectPrivilege(String checkedDel){
    	boolean flag=false;
    	checkedDel=checkedDel.substring(0, checkedDel.length() - 1);
    	String[] arry=null;
    	arry=checkedDel.split(",");
    	List<Integer> list=new ArrayList<Integer>();
    	for(int i=0;i<arry.length;i++){
    		list.add(Integer.parseInt(arry[i]));
    	}
    	try {
    		flag = sysPrivilegeService.delSelectPrivilege(list);
    	} catch (Exception e) {
    		logger.error(e,e);
    	}
    	return JSONMapper.createReturnMap(null, null, flag);
    }
    /**
     * 获取页面的操作权限
     * @author: 李海宁
     * @date: 2016年10月21日 下午1:57:20
     * @param url 当前页面的url
     * @param map
     * @return ModelMap
     */
    @ResponseBody
    @RequestMapping(value="findActionPri")
    public ModelMap findActionPri(String url,HttpServletRequest request){
    	String path = request.getContextPath()+"/";
    	ModelMap map = new ModelMap();
    	if(path.length()>1){
    		url = url.split(path)[1];
    	}else{
    		url = url.substring(url.indexOf('/', 8)+1);
    	}
    	url = url.substring(0,url.indexOf(".do")+3);
		try {
			String actionPri = sysPrivilegeRoleService.findActionPri(Integer.valueOf(getCurrentStaffVO().getRoleId()), url);
			map.put("actionPri", actionPri);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
    }
}